<template >
  <div class="wrap">
    <div class="left-wrap" >
      <div class="left-item" style="color:red">Text Lines</div>
      <div v-for="(item, index) in xml.lines" 
        :key="index" 
        :class="item.isActive ? 'left-item active-item' : 'left-item'"
        @click="handleClick(index)"
        >
        {{ item.value.length > 10 
          ? item.value.substring(0, 10) + '...'
          : item.value 
        }}
      </div>
    </div>
    <div class="right-wrap">
      <canvas id="canvas"
      :width="xml.width"
      :height="xml.height"
      style="border:1px solid blue">
        抱歉，您的浏览器不支持canvas元素.
      </canvas>
    </div>
  </div>
</template>

<script>
import { debuglog } from 'util';

export default {
  name: 'DrawImage',
  props: {
    msg: String
  },
  data() {
    return {
      xml: {
        width: '',
        height: '',
        lines: []
      },
      selectIndex: 0,
      imgURL: './source1.jpg'
    }
  },
  methods: {
    getXML(url) {
      const req = new XMLHttpRequest();
      req.open('GET', url, false);
      req.send();
      return req.responseXML;
    },
    drawImage(imgURL) {
      let canvas = document.getElementById('canvas');
      let ctx = canvas.getContext("2d");
      let img = new Image();
      img.src = imgURL;
      let width = this.xml.width;
      let height = this.xml.height;
      let lines = this.xml.lines;
      img.onload = () => {
        let rate = (width < height ? width / height : height / width) / 4;
        canvas.width = width * rate; 
        canvas.height = height * rate; 
        ctx.rotate(30 * Math.PI / 180);
        ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate);

        // 得出缩放比例，根据缩放比例同步缩放坐标轴
        let num = width / (width * rate);

        for (let index = 0; index < lines.length; index++) {
          let item = lines[index];
          ctx.beginPath();
          ctx.strokeStyle = index == this.selectIndex ? "red" : "yellow";
          const polygon = item.polygon;
          let beginPoint = polygon[0];

          ctx.moveTo(parseInt(beginPoint.x / num), parseInt(beginPoint.y / num));
          for (let i = 1; i < polygon.length; i++) {
            ctx.lineTo(parseInt(polygon[i].x / num), parseInt(polygon[i].y / num));
          }

          ctx.closePath();
          // 完成绘制直线
          ctx.stroke();

          // 绘制tag
          if (index == this.selectIndex) {
            let tag = lines[index].value;
            ctx.fillStyle = 'red';
            ctx.font = 'bold 35px Adobe Ming Std';
            let pointLength = lines[index].polygon.length;
            let lastIndex = pointLength - 1;
            let lastPoint = lines[index].polygon[lastIndex];
            let x = parseInt(lastPoint.x / num) - 10;
            let y = parseInt(lastPoint.y / num) + 30;
            ctx.fillText(tag, x, y);
            ctx.stroke();
          } 
        }
      }
    },
    splitPoints(p) {
      const points = p.split(" ");
      let _points_ = [];
      for (let i = 0, j = 1; i < points.length; i += 2, j += 2) {
        let x = points[i];
        let y = points[j];
        _points_.push({ x, y });
      }
      return _points_;
    },
    xmlParse(xmlSource) {
      this.xml.width = xmlSource.getElementsByTagName("Width")[0].childNodes[0].nodeValue;
      this.xml.height = xmlSource.getElementsByTagName("Height")[0].childNodes[0].nodeValue;
      const linesRoot = xmlSource.getElementsByTagName("Lines");
      const lines = linesRoot[0].getElementsByTagName("Line");
      for (let i = 0; i < lines.length; i++) {
        let line = {};
        let points = [];
        points = this.splitPoints(lines[i].getElementsByTagName("Polygon")[0].childNodes[0].nodeValue);

        line.isActive = i == 0 ? true : false;
        line.id = lines[i].getElementsByTagName("Id")[0].childNodes[0].nodeValue;
        line.tag= lines[i].getElementsByTagName("Tag")[0].childNodes[0].nodeValue;
        line.isConfirm = lines[i].getElementsByTagName("IsConfirm")[0].childNodes[0].nodeValue;
        line.confidence = lines[i].getElementsByTagName("Confidence")[0].childNodes[0].nodeValue;
        line.polygon = points;
        line.polyType = lines[i].getElementsByTagName("PolyType")[0].childNodes[0].nodeValue;
        line.value = lines[i].getElementsByTagName("Value")[0].childNodes[0] 
        ? lines[i].getElementsByTagName("Value")[0].childNodes[0].nodeValue
        : '空';
        this.xml.lines.push(line);
      }
    },
    handleClick(index) {
      this.selectIndex = index;
      for (let i = 0; i < this.xml.lines.length; i++) {
        if (i != index) {
          this.xml.lines[i].isActive = false;
        } else {
          this.xml.lines[i].isActive = true;
        }
      }
      this.drawImage(this.imgURL);
    },
    handleKeyup() {
      let len = this.xml.lines.length;
      if (this.selectIndex == 0) {
        this.selectIndex = len -1;
        this.handleClick(this.selectIndex);
      } else {
        this.selectIndex = this.selectIndex - 1;
        this.handleClick(this.selectIndex);
      }
    },
    handleKeydown() {
      let len = this.xml.lines.length;
      if (this.selectIndex == len -1) {
        this.selectIndex = 0;
        this.handleClick(this.selectIndex);
      } else {
        this.selectIndex = this.selectIndex + 1;
        this.handleClick(this.selectIndex);
      }
    }
  },
  created() {
    document.onkeydown = ({ keyCode }) => {
      if (keyCode == 38) {
        this.handleKeyup();
      }
      if (keyCode == 40) {
        this.handleKeydown();
      }
    }
  },
  mounted() {
    const rep = this.getXML('./data1.xml');
    this.xmlParse(rep);
    this.drawImage(this.imgURL);
  }
}
</script>

<style>
.wrap {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
}
.left-wrap {
  width: 40%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.left-item {
  width: 120px;
  height: 40px;
  border: 1px solid #AAA;
  text-align: center;
  font-size: 18px;
}
.active-item {
  background-color: #BBB;
}
.right-wrap {
  width: 800px;
  height: 600px;
}
img {
  width: 100%;
  height: 100%;
}
</style>

